package com.zyf.channel.plugin

import org.gradle.api.Project
import java.io.File

object ApkSignUtils {
    fun getBuildTool(tool: String,project: Project): String {
        val sdkRoot = getAndroidSdkDir(project)
        val buildToolsDir = File(sdkRoot, "build-tools").listFiles()
            ?.sortedByDescending { it.name }?.firstOrNull()
            ?: error("未找到 build-tools 目录")
        return File(buildToolsDir, tool).absolutePath
    }

    fun runCommand(command: List<String>) {
        val process = ProcessBuilder(command)
            .inheritIO()
            .start()
        val exitCode = process.waitFor()
        if (exitCode != 0) error("命令失败: ${command.joinToString(" ")}")
    }

    private fun getAndroidSdkDir(project: Project):String{
        val localProperties = File(project.rootDir, "local.properties")
        if (localProperties.exists()) {
            val props = java.util.Properties()
            localProperties.inputStream().use { props.load(it) }
            val sdkDir = props.getProperty("sdk.dir")
            if (!sdkDir.isNullOrEmpty()) {
                return sdkDir
            }
        }

        // fallback
        val env = System.getenv("ANDROID_HOME")
        if (!env.isNullOrEmpty()) {
            return env
        }
        error("无法找到 Android SDK，请确保 local.properties 中有 sdk.dir，或设置 ANDROID_HOME 环境变量。")
    }
}